package com.webdrop.gui;

import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.webdrop.client.UrlToServer;

public class LoginWidget extends Composite
{
	private DialogBox loginDialog;

	private boolean loginFormFilled = false;

	UrlToServer urlToServer = new UrlToServer();

	/**
	 *  Show the dialogbox with the google logo to login
	 */
	public LoginWidget()
	{
		VerticalPanel base = new VerticalPanel();

		loginDialog = new DialogBox();
		loginDialog.setText("Login WebDrop");

		VerticalPanel loginPanel = new VerticalPanel();
		loginDialog.setWidget(loginPanel);

		HTML loginForm = new HTML(
				"<form method=\"post\" action=\"" + urlToServer.getUrlToServer()+"login.php\" id=\"openid\">" +
						"<input type=\"hidden\" name=\"client_url\" value=\"" + Window.Location.getHref().split("#")[0] + "\">" +
						"</form>"
				);

		loginForm.addAttachHandler(new AttachEvent.Handler() 
		{
			public void onAttachOrDetach(AttachEvent event) 
			{
				if (!loginFormFilled)
				{
					fillLoginForm();
					loginFormFilled = true;
				}
			}
		});

		loginPanel.add(loginForm);

		initWidget(base);
	}


	protected void onLoad() 
	{
		super.onLoad();
		// Show dialog
		loginDialog.center();
	}


	protected void onUnload() 
	{
		super.onUnload();
		// Hide dialog
		loginDialog.hide();
	}

	public static native void fillLoginForm() /*-{
 		$wnd.$('#openid').openid();
	}-*/;
}